const express = require('express');
const router = express.Router();
const articleService = require('@/services/articleService');
const validateChecks = require('@/middlewares/validatorPayload');
const { check, param } = require('express-validator');

router.post('/create', validateChecks([
    check('title', '标题不能为空').notEmpty(),
    check('content', '内容不能为空').notEmpty(),
]), async function (req, res, next) {
    try {
        await articleService.articleCreate(req.body);
        res.createResponse(200, '创建成功');
    } catch (err) {
        res.createResponse(500, err.message);
    }
});

router.delete('/delete', validateChecks([
    check('id', '文章id不能为空').notEmpty(),
]), async function (req, res, next) {
    try {
        await articleService.articleDelete(req.query);
        res.createResponse(200, '删除成功');
    } catch (err) {
        res.createResponse(500, err.message);
    }
});

router.put('/update/:id', validateChecks([
    param('id', '文章id内容为空'),
]), async function (req, res, next) {
    try {
        const updatedFields = req.body;
        const { id } = req.params;
        await articleService.articleUpdate({ _id: id, updatedFields } );
        res.createResponse(200, '修改成功');
    } catch (err) {
        res.createResponse(500, err.message);
    }
});


router.get('/query', validateChecks([
    // check('title').withMessage('标题不能为空'),
    param('page').optional().isInt({ min: 1 }).withMessage('页码必须是大于等于1的整数'),
    param('pageSize').optional().isInt({ min: 1 }).withMessage('每页数量必须是大于等于1的整数'),
]), async function (req, res, next) {
    try {
        let data = await articleService.articleQuery(req.query);
        res.createResponse(200, '查询成功', data);
    } catch (err) {
        res.createResponse(500, err.message);
    }
});

module.exports = router;